import {observer} from 'mobx-react';
import {observable} from 'mobx';

import {WeaLeftRightLayout, WeaLocaleProvider, WeaSlideModal, WeaTextarea} from 'ecCom';

import {Button, message, Spin} from 'antd';
import FieldError from "../../designer/form/view/field/Error";
import FieldView from "../../designer/form/view/field/View";
import {viewTypes} from "../../../constants/form";
import fillin from "../../../apis/fillin";
import DATAAPI from '../../../apis/data';

const { getLabel } = WeaLocaleProvider;

@observer export default class HtmlDataPanel extends React.Component {
  @observable editRemark = 1;
  @observable editForm = false;
  @observable formid = '';
  @observable dataId = '';
  @observable isSaving = false;
  @observable remark = '';

  componentWillReceiveProps() {
    const {comps} = this.props.detailData;
    if(!comps) {
      this.editForm = false;
    }
  }

  onEditStateChange(edit) {
    this.editRemark = edit ? 2 : 1;
  }

  onRemarksChange = value => {
    this.remark = value;
  }

  handleRemarksChange = () => {
    const value = this.remark;

    let formData = new FormData();
    formData.append("remark", value);
    formData.append("formId", this.formid);
    formData.append("dataId", this.dataId);

    const { sys } = this.props.detailData;
    sys.remark = value;

    fillin.modifyRemark(formData).then((res) => {
      message.success(getLabel('0', '修改成功'))
    }).catch((e) => {
      console.log(e);
    });

    this.onEditStateChange(false);
  }

  getLeftMainView(components) {
    if(!components) return null;

    return (
      <div className='wea-edc-fv-main'>
        <div className='wea-edc-fv-body clearfix'>
          {components.filter(com => !com.pid).map(com => (
            <FieldError key={com.uuid} error={com.errorCom ? com.errorCom.error : com.error} >
              {this.getFieldView(com)}
            </FieldError>
          ))}
        </div>
      </div>
    )
  }

  getFieldView(com) {
    const viewType = !this.editForm && viewTypes.READONLY || viewTypes.PC;
    if(com.config.complex) {
      return (
        <FieldView
          key={com.uuid}
          viewType={viewType}
          field={com}
          dataPanle={true}
        />
      );
    }
    return (
      <FieldView
        key={com.uuid}
        viewType={viewType}
        field={com}
        dataPanle={true}
        toggleFooterDisable={() => { }}
        onChange={(value) => {
          this.handleValChange(value, com);
        }}
        dataPanel={true}
      />
    );
  }

  handleValChange(value, com) {
    com.value = value;
  }

  onSubmit = () => {
    if(this.isSaving) return;

    this.isSaving = true;

    const { detailData, reloadData } = this.props;
    const { comps } = detailData;

    const newComs = comps.map(({ fieldname, value, fieldid, type }) => {

      if((type == "PICTURE" || type == "ATTACHMENT") && value) {
        let docIds = [];
        value.forEach(({ docid }) => {
          docid > 0 && (docIds.push(docid));
        });
        value = docIds.join(',');
      }

      return { fieldname, value, fieldid, type };
    })

    const formdata = new FormData();
    formdata.append('formid', this.formid);
    formdata.append('id', this.dataId);
    formdata.append('datas', JSON.stringify(newComs));

    DATAAPI.update(formdata).then(() => {
      message.success(getLabel('0', '修改成功'));
      reloadData();
      this.editForm = false;
      this.isSaving = false;
    }).catch(() => {
      message.error(getLabel('0', '修改数据异常'));
      this.isSaving = false;
    });
  }

  onClose = () => {
    const { close } = this.props;
    this.editForm = false;
    this.onEditStateChange(false);
    close();
  }

  renderContent() {
    const { props, editRemark, isSaving } = this;
    const { detailData, rightLevel } = props;
    const { comps, sys } = detailData;
    const editRight = rightLevel == 2;

    return (
      <Spin spinning={!comps || isSaving}>
        <WeaLeftRightLayout
          leftWidth={550}
          showBtn={false}
          leftCom={this.getLeftMainView(comps)}
        >

          <div className="modal-right-wrapper">
            <div className="modal-right-header">
              <div className="title">基本信息</div>
              <div className="function-button">
              </div>
            </div>
            <div className="entry-info-section">
              <dl>
                <dt>序号：</dt>
                <dd>{sys.id}</dd>
              </dl>
              <dl>
                <dt>提交人：</dt>
                <dd>{sys.creator}</dd>
              </dl>
              <dl>
                <dt>提交时间：</dt>
                <dd>{sys.createdate} {sys.createtime}</dd>
              </dl>
              <dl>
                <dt>填写设备：</dt>
                <dd>{sys.clientdevice}</dd>
              </dl>
              <dl>
                <dt>操作系统：</dt>
                <dd>{sys.clientos}</dd>
              </dl>
              <dl>
                <dt>浏览器：</dt>
                <dd>{sys.clientbrowser}</dd>
              </dl>
              <dl>
                <dt>IP：</dt>
                <dd>{sys.ip}</dd>
              </dl>
            </div>
            <div className="entry-remark-split-line"></div>

            {
              sys.wxopenid ?
                <div>
                  <div className="modal-right-header">微信信息</div>
                  <div className="weixin-info">
                    <img src={sys.wxheadimgurl} className="avatar" />
                    <div className="info-container">
                      <span>昵称：{sys.wxnickname}</span>
                      <br />
                      <span>性别：{sys.wxsex}</span>
                      <span>省市：{sys.wxprovince} {sys.wxcity} </span>
                    </div>
                  </div>

                  <div className="entry-remark-split-line"></div>
                </div>
                : null
            }


            <div className="entry-remark-container">
              <div className="edit-container">
                {
                  (editRight && !sys.remark) ?
                    <a className="add-remark" onClick={() => { this.onEditStateChange(true) }}>
                      {
                        (editRemark == 1) && <i className="icon-edc-f-edit wea-edc-input-icon"></i>
                      }
                      添加备注
                      </a>
                    :
                    <div className="modal-right-header">数据备注</div>

                }
              </div>
              <WeaTextarea
                style={{ height: '150' }}
                viewAttr={editRight ? editRemark : 1}
                value={sys.remark}
                onChange={this.onRemarksChange}
                ref={'remark'} />
              {editRight ?
                editRemark != 1 &&
                <div><span onClick={this.handleRemarksChange} className="edit-btn edit-btn-save">保存</span>
                  <span className="edit-btn" onClick={() => { this.onEditStateChange(false) }}>取消</span></div>
                || (sys.remark && <span onClick={() => { this.onEditStateChange(true) }} className="edit-btn">修改</span>)
                : null
              }
            </div>

          </div>
        </WeaLeftRightLayout>
      </Spin>
    );
  }

  render() {
    const { props, isSaving, editForm, onSubmit, onClose } = this;
    const { visible, detailData, rightLevel } = props;
    const { sys } = detailData;

    const editRight = rightLevel == 2;
    const buttons = editRight ? (!editForm && [
      (<Button type="primary" loading={isSaving} onClick={() => { this.editForm = true }}>{getLabel(504304, "修改")}</Button>),
      (<Button type="ghost" onClick={onClose}>{getLabel(31129, "取消")}</Button>)
    ] || [
      isSaving ? (<Button type="primary" loading={isSaving} disabled>{getLabel(0, "提交")}</Button>) : (<Button type="primary" loading={isSaving} onClick={onSubmit}>{getLabel(0, "提交")}</Button>),
        (<Button type="ghost" onClick={() => { this.editForm = false }}>{getLabel(31129, "取消")}</Button>)
      ]) : [
        (<Button type="ghost" onClick={onClose}>{getLabel(0, "关闭")}</Button>)
      ];

    this.formid = sys.formid;
    this.dataId = sys.id;
    return (
      <WeaSlideModal
        onClose={onClose}
        className="edc-html-datapanel"
        visible={visible}
        width={'800'}
        height={100}
        direction={'right'}
        measureY={'%'}
        title={<div><div className="title-close-div" onClick={onClose}><span className="title-close"></span></div><div className={'title-btns'}>{buttons}</div></div>}
        content={this.renderContent()}
        hasScroll={false}
      >
      </WeaSlideModal>
    );
  }
}